package io.gitee.tziye.spring;

import io.gitee.tziye.core.instance.InstanceSpec;
import io.gitee.tziye.core.instance.RenaiDataSource;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;

import static io.gitee.tziye.common.Constants.DEFAULT;

@ConfigurationProperties(prefix = "renai-data")
@Data
public class RenaiProperties {

    private String url;
    private String database;
    private String user;
    private String password;
    private int maxConnections = 10;
    private int maxIdleSeconds = 10 * 60;

    private String group = DEFAULT;
    // 默认为spring.application.name
    private String service;
    // 默认为server.port
    private int port;

    public RenaiDataSource dataSource() {
        if (StringUtils.isAnyBlank(url, database, user, password)) {
            return null;
        }
        RenaiDataSource dataSource = new RenaiDataSource(url, database, user, password);
        if (maxConnections > 0) {
            dataSource.setMaxConnections(maxConnections);
        }
        if (maxIdleSeconds > 0) {
            dataSource.setMaxIdleSeconds(maxIdleSeconds);
        }
        return dataSource;
    }

    public InstanceSpec instance() {
        InstanceSpec instance = new InstanceSpec();
        if (StringUtils.isNotBlank(group)) {
            instance.setGroup(group);
        }
        if (StringUtils.isNotBlank(service)) {
            instance.setService(service);
        }
        if (port > 0) {
            instance.setPort(port);
        }
        return instance;
    }

}
